package com.iwith.dongmoon.listadpater;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.iwith.dongmoon.activity.MainTabView;
import com.iwith.dongmoon.activity.R;
import com.iwith.dongmoon.gsonlist.MainIconItem;

public class MainIconGridAdapter extends ArrayAdapter<MainIconItem> {
	private Context mContext;
	private ArrayList<MainIconItem> items;
	private LayoutInflater mInflater;

	public MainIconGridAdapter(Context context, int textViewResourceId,	ArrayList<MainIconItem> list) {
		super(context, textViewResourceId, list);
		// TODO Auto-generated constructor stub

		this.mContext = context;
		this.items = list;
		this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	class ViewHolder {
		ImageView iconImage;
		TextView name;
	}

	@Override
	public MainIconItem getItem(int position) {
		if(items==null) 	return null;
		else 				return items.get(position);
	}
	
	@Override
	public int getCount(){
		if(items==null)		return 0;
		else				return super.getCount();
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.griditem_icon, null);
			holder.iconImage = (ImageView) convertView.findViewById(R.id.griditemicon_iconimage);
			holder.name = (TextView) convertView.findViewById(R.id.griditemicon_groupname);
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final MainIconItem item = items.get(position);

		if (item != null) {
			if(item.getImage()!=null){
				holder.iconImage.setImageResource(item.getImage());
			}
			holder.name.setText(item.getIconName());
		}
		final int pos=position;
		convertView.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(mContext, MainTabView.class);
				intent.putExtra("tab_position", pos);
				//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				mContext.startActivity(intent);
				
				if(item.getFlag()==true){
					((Activity) mContext).finish();
				}
			}
		});

		return convertView;
	}
}
